import 'package:flutter/material.dart';
import '../services/posts_service.dart';
import '../services/upload_service.dart';
import '../services/token_manager.dart';

class AddPostPage extends StatefulWidget {
  const AddPostPage({super.key});

  @override
  State<AddPostPage> createState() => _AddPostPageState();
}

class _AddPostPageState extends State<AddPostPage> {
  final _formKey = GlobalKey<FormState>();
  final _titleController = TextEditingController();
  final _contentController = TextEditingController();
  final List<String> _imageUrls = [];
  final PostsService _postsService = PostsService();
  final UploadService _uploadService = UploadService();
  bool _isSubmitting = false;

  @override
  void dispose() {
    _titleController.dispose();
    _contentController.dispose();
    super.dispose();
  }

  Future<void> _submit() async {
    if (!_formKey.currentState!.validate()) return;

    setState(() {
      _isSubmitting = true;
    });

    // 获取当前登录用户信息
    final userInfo = await TokenManager.instance.getUserInfo();
    final userName = userInfo['username'] ?? '用户';

    final ok = await _postsService.savePost(
      title: _titleController.text.trim(),
      content: _contentController.text.trim(),
      userName: userName,
      imageUrls: _imageUrls,
    );

    setState(() {
      _isSubmitting = false;
    });

    if (!mounted) return;

    if (ok) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('🎉 帖子发布成功！'), backgroundColor: Colors.green),
      );
      Navigator.pop(context, true);
    } else {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('❌ 发布失败，请重试'), backgroundColor: Colors.red),
      );
    }
  }

  // 删除某张图片
  void _removeImage(String url) {
    setState(() {
      _imageUrls.remove(url);
    });
  }

  // 添加新图片
  Future<void> _pickAndUploadImages() async {
    final files = await _uploadService.pickImages();
    if (files.isEmpty) return;

    try {
      final urls = await _uploadService.uploadImages(files);
      if (!mounted) return;

      setState(() {
        _imageUrls.addAll(urls);
      });

      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('✅ 成功上传 ${urls.length} 张图片')),
      );
    } catch (e) {
      if (!mounted) return;
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('❌ 上传失败: $e')),
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context);

    return Scaffold(
      appBar: AppBar(
        title: const Text(
          '撰写新帖',
          style: TextStyle(fontWeight: FontWeight.bold),
        ),
        elevation: 0,
        backgroundColor: theme.colorScheme.surface.withOpacity(0.95),
        foregroundColor: theme.colorScheme.primary,
        centerTitle: true,
        actions: [
          IconButton(
            onPressed: () {
              if (_formKey.currentState?.validate() ?? false) {
                _submit();
              }
            },
            icon: const Icon(Icons.send_rounded, size: 20),
            tooltip: '快速发布',
          )
        ],
      ),
      body: Container(
        color: theme.colorScheme.background,
        child: SafeArea(
          top: false,
          child: Padding(
            padding: const EdgeInsets.all(16.0),
            child: Form(
              key: _formKey,
              child: Column(
                children: [
                  Expanded(
                    child: ListView(
                      padding: EdgeInsets.zero,
                      children: [
                        // 标题输入
                        Card(
                          elevation: 2,
                          shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
                          child: Padding(
                            padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
                            child: TextFormField(
                              controller: _titleController,
                              decoration: InputDecoration(
                                hintText: '给帖子起个吸引人的标题...',
                                border: InputBorder.none,
                                prefixIcon: const Icon(Icons.title_outlined, color: Colors.grey),
                                hintStyle: const TextStyle(color: Colors.grey, fontSize: 14),
                              ),
                              textInputAction: TextInputAction.next,
                              validator: (value) {
                                if (value == null || value.trim().isEmpty) return '请输入标题';
                                if (value.trim().length > 100) return '标题不能超过100字符';
                                return null;
                              },
                            ),
                          ),
                        ),

                        const SizedBox(height: 16),

                        // 内容输入
                        Card(
                          elevation: 2,
                          shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
                          child: Padding(
                            padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
                            child: TextFormField(
                              controller: _contentController,
                              decoration: InputDecoration(
                                hintText: '分享你的想法吧...',
                                border: InputBorder.none,
                                prefixIcon: const Padding(
                                  padding: EdgeInsets.only(top: 10),
                                  child: Icon(Icons.edit_note_outlined, color: Colors.grey),
                                ),
                                hintStyle: const TextStyle(color: Colors.grey),
                                alignLabelWithHint: true,
                              ),
                              maxLines: 8,
                              textInputAction: TextInputAction.newline,
                              validator: (value) {
                                if (value == null || value.trim().isEmpty) return '请输入内容';
                                if (value.trim().length > 5000) return '内容太长了';
                                return null;
                              },
                            ),
                          ),
                        ),

                        const SizedBox(height: 20),

                        // 图片上传区
                        Card(
                          elevation: 2,
                          shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
                          child: Padding(
                            padding: const EdgeInsets.all(16.0),
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Row(
                                  children: [
                                    const Icon(Icons.photo_library_outlined, color: Colors.blue),
                                    const SizedBox(width: 8),
                                    Expanded(
                                      child: Text(
                                        '添加图片',
                                        style: theme.textTheme.titleMedium?.copyWith(fontWeight: FontWeight.w600),
                                      ),
                                    ),
                                  ],
                                ),
                                const SizedBox(height: 12),
                                OutlinedButton.icon(
                                  onPressed: _isSubmitting ? null : _pickAndUploadImages,
                                  icon: const Icon(Icons.add_a_photo, size: 18),
                                  label: const Text("选择图片"),
                                  style: OutlinedButton.styleFrom(
                                    padding: const EdgeInsets.symmetric(vertical: 10, horizontal: 16),
                                    side: BorderSide(color: theme.colorScheme.primary),
                                  ),
                                ),
                                const SizedBox(height: 16),

                                // 图片预览网格
                                if (_imageUrls.isNotEmpty)
                                  Wrap(
                                    spacing: 10,
                                    runSpacing: 10,
                                    children: _imageUrls.map((url) {
                                      return Stack(
                                        children: [
                                          ClipRRect(
                                            borderRadius: BorderRadius.circular(8),
                                            child: Image.network(
                                              url,
                                              width: 90,
                                              height: 90,
                                              fit: BoxFit.cover,
                                              loadingBuilder: (context, child, loadingProgress) {
                                                if (loadingProgress == null) return child;
                                                return Container(
                                                  width: 90,
                                                  height: 90,
                                                  color: Colors.grey[200],
                                                  child: Center(child: CircularProgressIndicator(strokeWidth: 2)),
                                                );
                                              },
                                            ),
                                          ),
                                          Positioned(
                                            top: -6,
                                            right: -6,
                                            child: IconButton(
                                              padding: EdgeInsets.zero,
                                              constraints: const BoxConstraints(),
                                              icon: const CircleAvatar(
                                                radius: 12,
                                                backgroundColor: Colors.redAccent,
                                                child: Icon(Icons.close, size: 16, color: Colors.white),
                                              ),
                                              onPressed: () => _removeImage(url),
                                            ),
                                          ),
                                        ],
                                      );
                                    }).toList(),
                                  ),
                              ],
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),

                  // 提交按钮
                  Padding(
                    padding: const EdgeInsets.only(top: 16),
                    child: SizedBox(
                      height: 52,
                      child: ElevatedButton(
                        onPressed: _isSubmitting ? null : _submit,
                        style: ElevatedButton.styleFrom(
                          shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
                          backgroundColor: theme.colorScheme.primary,
                          foregroundColor: Colors.white,
                          elevation: 3,
                        ),
                        child: _isSubmitting
                            ? const SizedBox(
                          width: 24,
                          height: 24,
                          child: CircularProgressIndicator(strokeWidth: 2, color: Colors.white),
                        )
                            : const Text(
                          "发布帖子",
                          style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
                        ),
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }
}